package com.example.shutdown_v1.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * MQTT测试控制器
 * 用于验证MQTT消息接收是否正常
 */
@RestController
@RequestMapping("/api/mqtt/test")
@Slf4j
@RequiredArgsConstructor
@CrossOrigin(originPatterns = "*")
public class MqttTestController {
    
    // 用于记录收到的MQTT消息
    private static volatile String lastReceivedMessage = "无消息";
    private static volatile String lastReceivedTopic = "无主题";
    private static volatile long lastReceivedTime = 0;
    
    /**
     * 供MqttMessageHandler调用，记录收到的消息
     */
    public static void recordMessage(String topic, String message) {
        lastReceivedTopic = topic;
        lastReceivedMessage = message;
        lastReceivedTime = System.currentTimeMillis();
        // 改为DEBUG级别，避免日志过多（一个数据包一条消息，频率极高）
        log.debug("[MQTT测试] 记录消息 - 主题:{}, 消息:{}", topic, message);
    }
    
    /**
     * 查看最后收到的MQTT消息
     */
    @GetMapping("/last-message")
    public ResponseEntity<Map<String, Object>> getLastMessage() {
        return ResponseEntity.ok(Map.of(
            "success", true,
            "lastTopic", lastReceivedTopic,
            "lastMessage", lastReceivedMessage,
            "lastTime", lastReceivedTime > 0 ? 
                java.time.Instant.ofEpochMilli(lastReceivedTime).toString() : "从未收到",
            "secondsAgo", lastReceivedTime > 0 ? 
                (System.currentTimeMillis() - lastReceivedTime) / 1000 : -1
        ));
    }
    
    /**
     * 清除消息记录
     */
    @PostMapping("/clear")
    public ResponseEntity<Map<String, Object>> clearMessages() {
        lastReceivedMessage = "已清除";
        lastReceivedTopic = "已清除";
        lastReceivedTime = 0;
        
        return ResponseEntity.ok(Map.of(
            "success", true,
            "message", "消息记录已清除"
        ));
    }
}
